const path = require('path')
const Jimp = require("jimp")
const Router = require('express').Router()
const { asyncHandle, getErr } = require('../util/util')

const multer = require('multer')
// const upload = multer({ dest: path.resolve(__dirname, '../public/upload/') })

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, path.resolve(__dirname, '../public/origin/'))
    },
    filename: function (req, file, cb) {
        // fieldname 字段名
        const ext = path.extname(file.originalname)
        const filename = file.fieldname + '-' + Date.now() + ext
        cb(null, filename)
    }
})

const upload = multer({
    storage: storage,
    limits: {
        fileSize: 100 * 1024 // 限制上传文件大小
    },
    fileFilter(req, file, cb) {
        //验证文件后缀名
        const extname = path.extname(file.originalname);
        const whitelist = [".jpg", ".gif", "png"];
        if (whitelist.includes(extname)) {
            cb(null, true);
        } else {
            cb(new Error(`your ext name of ${extname} is not support`));
        }
    },
})

const waterPath = path.resolve(__dirname, '../public/upload/water.jpg')

// 文件上传
Router.post('/', upload.single('file'), asyncHandle(async (req, res) => {
    // 加水印
    const originPath = req.file.path
    const targetPath = path.resolve(__dirname, '../public/upload', req.file.filename)
    await mark(waterPath, originPath, targetPath)
    return {
        url: '/upload/' + req.file.filename
    }
}))

module.exports = Router


/**
 *给一张图片加水印
 * @param {*} waterFile 水印图片
 * @param {*} originFile 原始图片
 * @param {*} targetPath 目标图片地址
 * @param {*} proportion 比例
 * @param {*} marginProportion 水印图片在目标图片位置的比例
 */
async function mark(waterFile, originFile, targetPath, proportion = 10, marginProportion = 0.05) {
    const [water, origin] = await Promise.all([Jimp.read(waterFile), Jimp.read(originFile)])

    // 对水印图片进行缩放
    // 原始图宽度/水印图宽度 = 10/2 = 5
    // 目标：10/1 = 10
    // 水印图要缩小 2
    const curProportion = origin.bitmap.width / water.bitmap.width;
    water.scale(curProportion / proportion)

    // 计算位置
    const right = origin.bitmap.width * marginProportion
    const bottom = origin.bitmap.height * marginProportion
    const x = origin.bitmap.width - right - water.bitmap.width
    const y = origin.bitmap.height - bottom - water.bitmap.height

    // 混合图片,写入水印
    origin.composite(water, x, y, {
        mode: Jimp.BLEND_SOURCE_OVER, // 水印在原图上面
        opacitySource: 0.3, // 水印透明度
        opacityDest: 1, // 原图透明度
    })

    // 保存图片
    await origin.write(targetPath)
}
